import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";
import qs from "qs";
import {getCookie, setCookie} from "../common/cookie";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    user:null,
    // {
    //   phone: '12191',
    //   password: '10088',
    //   regTime:1653790677837,
    //   id:1,
    //   name:"刘华强",
    // },
    cart: {
      id: 0,
      items: [],
      totalPrice: 0.0
    },
    /* 搜索结果 */
    search: null,
    orders: [],
    discount:[],
    order_item:[],
    order_id:0,
    order_index:0
  },
  mutations: {
    updateUser(state, user) {
      if (user == null) return
      state.user = user
    },
    updateCart(state, cart) {
      if (cart == null) return
      state.cart = cart
    },
    updateSearch(state, search) {
      if (search == null) return
      state.search = search
    },
    updateOrders(state, orders) {
      if (orders == null) return
      state.orders = orders
    },
    successLogin(state,user){
      if (user == null) return
      state.user = user
      setCookie('phone', user.phone, 7)
      setCookie('password', user.password, 7)
    }
  },
  actions: {
    /* 模拟登陆，用于开发阶段获取用户数据 */
    tryAutoLogin(context, payload) {
      let phone = getCookie('phone')
      let password = getCookie('password')
      if (phone == null || password == null) {
        console.log('cookie is null...')
        if (payload.onFailure != null) payload.onFailure()
        return
      }
      console.log('try auto login...')

      axios.post(
        '/login',
        qs.stringify({
          phone: phone,
          password: password,
          // phone: '12191',
          // password: '10088',
        })
      ).then((res) => {
        console.log('[/login] 获取成功...')
        console.log(res.data)
        if (!res.data.result) {
          if (payload.onFailure != null) payload.onFailure()
          return
        }
        context.commit('updateUser', res.data.user)
        if (payload.onResponse != null) payload.onResponse()
      }).catch(function (error) {
        console.log('[/login] 获取失败...')
        console.log(error)
        if (payload.onFailure != null) payload.onFailure()
      })
    },
  }
})
